import React, { useState, useEffect } from "react";
import { message, Table, Tree, Tag, Spin } from "antd";
import styles from "./index.less";
import { get4AChildOrgByParentOrgId } from "../../../../services/acceptGroup";

const { TreeNode } = Tree;

const UsersSelect = props => {
  const {
    orgsOfSelected: listOfSelectedOrgs,
    setorgsOfSelected: setlistOfSelectedOrgs
  } = props;
  const [listOfChildOrgs, setlistOfChildOrgs] = useState([]);
  const [loading, setLoading] = useState(false);
  const [spinLoading, setspinLoading] = useState(true);
  const [orgTreeData, setorgTreeData] = useState([]);

  useEffect(() => {
    getOrgTree();
    return () => {};
  }, []);

  function getOrgTree() {
    get4AChildOrgByParentOrgId().then(res => {
      setorgTreeData(
        res.datas.map(d => ({ ...d, title: d.orgName, key: d.orgId }))
      );
      setspinLoading(false);
    });
  }
  /* eslint no-param-reassign: ["error", { "props": false }] */
  const onLoadData = treeNode =>
    new Promise(resolve => {
      if (treeNode.props.children && treeNode.props.children.length > 0) {
        resolve();
        return;
      }
      get4AChildOrgByParentOrgId({ parentOrgId: treeNode.props.eventKey }).then(
        res => {
          const { datas, errCode, errMsg } = res;
          if (errCode === 0) {
            treeNode.props.dataRef.children = datas.map(d => ({
              ...d,
              key: d.orgId,
              title: d.orgName
            }));
            setorgTreeData([...orgTreeData]);
          } else {
            message.error(errMsg);
          }
          resolve();
        }
      );
    });
  // 树节点选中项变更事件 key:resourceId
  function onOrgTreeSelect(key, { selected }) {
    if (!selected) {
      setlistOfChildOrgs([]);
      return;
    }
    setLoading(true);
    // 获取子组织用于展示、
    get4AChildOrgByParentOrgId({ parentOrgId: key }).then(res => {
      const { datas, errCode, errMsg } = res;
      if (errCode === 0) {
        setlistOfChildOrgs(datas);
      } else {
        message.error(errMsg);
      }
      setLoading(false);
    });
  }
  // 树节点选中事件
  const onOrgTreeCheck = (_, { checked, node }) => {
    window.console.log(node);
    // 更新tag列表
    if (checked) {
      if (!listOfSelectedOrgs.find(o => +o.orgId === +node.props.eventKey)) {
        setlistOfSelectedOrgs(
          listOfSelectedOrgs.concat([
            { orgId: +node.props.eventKey, orgName: node.props.title }
          ])
        );
      }
    } else {
      setlistOfSelectedOrgs(
        listOfSelectedOrgs.filter(o => +o.orgId !== +node.props.eventKey)
      );
    }
  };
  // 已选中组织删除事件
  const onTagDel = key => {
    // 更新tag列表
    setlistOfSelectedOrgs(listOfSelectedOrgs.filter(o => o.orgId !== key));
  };
  // 渲染树子节点
  const renderTreeNodes = data =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.title} key={item.key} dataRef={item}>
            {renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.key} {...item} dataRef={item} />;
    });

  // 子组织表格column
  const orgColumn = [
    { dataIndex: "orgId", title: "组织ID" },
    { dataIndex: "orgName", title: "组织名称" }
  ];
  window.console.log(listOfSelectedOrgs);
  return (
    <div className={styles.root}>
      <Spin spinning={spinLoading}>
        <div className={styles.section}>
          <div
            style={{
              width: 230,
              display: "flex",
              flexFlow: "column"
            }}
          >
            <div>组织信息</div>
            <Tree
              checkable={true}
              loadData={onLoadData}
              onSelect={onOrgTreeSelect}
              checkStrictly
              checkedKeys={listOfSelectedOrgs.map(o => o.orgId)}
              onCheck={onOrgTreeCheck}
              className={styles.orgTree}
            >
              {renderTreeNodes(orgTreeData)}
            </Tree>
          </div>
          <div style={{ flex: 1 }}>
            <div>子组织信息</div>
            <div className={styles.menuTable}>
              <Table
                rowKey="orgId"
                columns={orgColumn}
                dataSource={listOfChildOrgs}
                pagination={{
                  pageSize: 5
                }}
                loading={loading}
              />
            </div>
          </div>
        </div>
      </Spin>
      <div style={{ padding: "16px 0px" }}>已选：</div>
      <div className={styles.selectedBox}>
        {listOfSelectedOrgs.map(rec => (
          <Tag
            style={{ marginBottom: 5 }}
            key={rec.orgId}
            closable
            visible={true}
            onClose={() => onTagDel(rec.orgId)}
          >
            （{rec.orgId}）{rec.orgName}
          </Tag>
        ))}
      </div>
    </div>
  );
};

export default UsersSelect;
